package cn.coisini.service.impl;

import cn.coisini.mapper.CarouselMapper;
import cn.coisini.model.common.dtos.Result;
import cn.coisini.model.common.enums.ResultEnum;
import cn.coisini.model.dto.CarouselDto;
import cn.coisini.model.pojo.Carousel;
import cn.coisini.model.vo.QueryVo;
import cn.coisini.service.CarouselService;
import cn.coisini.utils.IdWorker;
import cn.coisini.utils.JwtUtil;
import cn.hutool.core.text.CharSequenceUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

import static cn.coisini.model.common.constants.AdminConstants.ACCOUNT_NORMAL;
/**
 * @author xiangshaw
 * Description: 轮播图业务实现层
 */
@Service
public class CarouselServiceImpl extends ServiceImpl<CarouselMapper, Carousel> implements CarouselService {

    // 添加轮播图
    @Override
    public Result<ResultEnum> addCarousel(CarouselDto carouselDto) {
        if (CharSequenceUtil.isBlank(carouselDto.getCarouselUrl())){
            return Result.error(ResultEnum.DATA_INVALID_PARAMETER);
        }
        Carousel carousel = new Carousel();
        carousel.setId(String.valueOf(new IdWorker().nextId()));
        carousel.setCarouselUrl(carouselDto.getCarouselUrl());
        carousel.setRedirectUrl(carouselDto.getRedirectUrl());
        carousel.setCarouselRank(carouselDto.getCarouselRank());
        carousel.setCreateUser(JwtUtil.getUserIdFromToken());
        carousel.setCreateTime(LocalDateTime.now());
        boolean b = save(carousel);
        return b ? Result.ok(ResultEnum.SUCCESS) : Result.error(ResultEnum.DATA_NOT_ADD);
    }

    // 根据id查询轮播图
    @Override
    public Result<Carousel> getCarousel(String carouselId) {
        if (CharSequenceUtil.isBlank(carouselId)) {
            return Result.error(ResultEnum.PARAM_ERROR);
        }
        Carousel carousel = getById(carouselId);
        return Optional.ofNullable(carousel)
                .map(Result::ok)
                .orElse(Result.error(ResultEnum.DATA_NOT_EXIST));
    }

    // 查询轮播图列表
    @Override
    public Result<Object> getCarouselList(QueryVo queryVo) {
        QueryWrapper<Carousel> wrapper =  buildQueryWrapper(queryVo);
        // 处理分页逻辑
        Page<Carousel> page = new Page<>(queryVo.getCurrent(), queryVo.getLimit());
        Page<Carousel> userPage = page(page, wrapper);
        Result<Object> result = new Result<>();
        result.setData(userPage);
        return result;
    }

    // 构建查询条件
    private QueryWrapper<Carousel> buildQueryWrapper(QueryVo queryVo) {
        QueryWrapper<Carousel> wrapper = new QueryWrapper<>();
        // 处理关键字模糊查询
        Optional.ofNullable(queryVo.getKeyword())
                .filter(CharSequenceUtil::isNotBlank)
                .ifPresent(keyword -> wrapper.and(x -> x
                        .like("carouselUrl", keyword)
                ));
        // 处理时间范围查询
        Optional.ofNullable(queryVo.getCreateTimeBegin())
                .filter(CharSequenceUtil::isNotBlank)
                .ifPresent(startTime -> wrapper.ge("create_time", startTime));
        Optional.ofNullable(queryVo.getCreateTimeEnd())
                .filter(CharSequenceUtil::isNotBlank)
                .ifPresent(endTime -> wrapper.le("create_time", endTime));
        // 删除标记
        wrapper.eq("del_flag", ACCOUNT_NORMAL)
                // 排序
                .orderByDesc("id");
        return wrapper;
    }

    // 删除轮播图
    @Override
    public Result<ResultEnum> deleteCarousel(String carouselId) {
        // 1.检查参数
        if (CharSequenceUtil.isBlank(carouselId)) {
            return Result.error(ResultEnum.DATA_INVALID_PARAMETER);
        }
        // 2.判断当前用户是否存在
        Carousel carousel = getById(carouselId);
        if (carousel == null) {
            return Result.error(ResultEnum.DATA_NOT_EXIST);
        }
        // 3.删除并判断结果
        boolean b = removeById(carousel);
        if (b) {
            return Result.ok(ResultEnum.SUCCESS, "轮播图删除成功");
        }
        return Result.error(ResultEnum.FAIL, "轮播图删除失败");
    }

    // 更新轮播图
    @Override
    public Result<ResultEnum> updateCarousel(CarouselDto carouselDto) {
        // 1.检查参数
        String carouselId = carouselDto.getId();
        if (carouselId == null) {
            return Result.error(ResultEnum.DATA_NOT_EXIST);
        }
        // 2.判断当前轮播图是否存在
        Carousel carousel = getById(carouselId);
        if (carousel == null) {
            return Result.error(ResultEnum.DATA_NOT_EXIST);
        }
        // 3.更新信息
        carousel.setCarouselUrl(carouselDto.getCarouselUrl());
        carousel.setRedirectUrl(carouselDto.getRedirectUrl());
        carousel.setCarouselRank(carouselDto.getCarouselRank());
        carousel.setUpdateUser(JwtUtil.getUserIdFromToken());
        carousel.setUpdateTime(LocalDateTime.now());
        // 4.更新信息
        if (updateById(carousel)) {
            return Result.ok(ResultEnum.SUCCESS);
        }
        return Result.error(ResultEnum.FAIL, "信息修改失败");
    }

    // 批量删除
    @Transactional
    @Override
    public Result<ResultEnum> batchRemove(List<String> ids) {
        List<Carousel> carousels = listByIds(ids);
        if (carousels.isEmpty()) {
            return Result.error(ResultEnum.DATA_NOT_EXIST);
        }
        // 批量删除
        int deletedCount;
        try {
            deletedCount = baseMapper.deleteBatchIds(ids);
        } catch (Exception e) {
            return Result.error(ResultEnum.FAIL, "轮播图删除失败");
        }
        // 检查删除结果并返回
        if (deletedCount == ids.size()) {
            return Result.ok(ResultEnum.SUCCESS, "轮播图批量删除成功");
        } else {
            return Result.error(ResultEnum.FAIL, "部分轮播图删除失败，已删除 " + deletedCount + " 个轮播图");
        }
    }
}
